package com.sharemarking.system.service.impl;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReadWriteLock;

@Service
public class MybatisCacheFactoryEhcacheImpl implements Cache,ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	
	private String id;
	private net.sf.ehcache.Cache c;
	
	public MybatisCacheFactoryEhcacheImpl() {
		
	}
	
	public MybatisCacheFactoryEhcacheImpl(String id) {
		this.id=id;
	}
	
	private net.sf.ehcache.Cache getCache(){
		if(c!=null)return c;
		CacheManager cm=applicationContext.getBean(CacheManager.class);
		cm.addCache(id);
		c=cm.getCache(id);
		return c;
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public void putObject(Object key, Object value) {
		getCache().put(new Element(key, value));
	}

	@Override
	public Object getObject(Object key) {
		Element ele=getCache().get(key);
		if(ele==null)return null;
		return ele.getObjectValue();
	}

	@Override
	public Object removeObject(Object key) {
		Object o=getObject(key);
		c.remove(key);
		return o;
	}

	@Override
	public void clear() {
		getCache().removeAll();
	}

	@Override
	public int getSize() {
		return getCache().getSize();
	}

	@Override
	public ReadWriteLock getReadWriteLock() {
		return null;
	}
	
	@Override
	public boolean equals(Object o) {
	    if (getId() == null) {
	      throw new CacheException("Cache instances require an ID.");
	    }
	    if (this == o) {
	      return true;
	    }
	    if (!(o instanceof Cache)) {
	      return false;
	    }
	
	    Cache otherCache = (Cache) o;
	    return getId().equals(otherCache.getId());
	}
	
	@Override
	public int hashCode() {
	    if (getId() == null) {
	      throw new CacheException("Cache instances require an ID.");
	    }
	    return getId().hashCode();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		MybatisCacheFactoryEhcacheImpl.applicationContext=applicationContext;
	}
	
}
